package com.ma.chapter4.t7;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestReentrantLock2
 * @Author: mayongqiang
 * @DATE 2022/3/14 20:55
 * @Description: 可打断!
 */
@Slf4j(topic = "m.TestReentrantLock2")
public class TestReentrantLock2 {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            try {
                //如果没有竞争,那么此方法就会获取到lock对象锁
                //如果有竞争,就会进入阻塞队列,可以被其他进程用interrupt()方法打断
                log.debug("尝试获得锁");
                //捕获异常，处理异常
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("等锁的过程中被打断");
                return;
            }
            try {
                //临界区
                log.debug("获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("main获得锁");
        t1.start();

        //try {
        //    sleep(1);
        //    t1.interrupt();
        //    log.debug("打断t1");
        //} finally {
        //    lock.unlock();
        //}
        lock.unlock();


    }
}
